/*
struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};
*/
class Solution {
public:
    TreeNode* ans;
    TreeLinkNode* GetNext(TreeLinkNode* p) {
        if(p->right) {
            p = p->right;
            while(p->left) {p=p->left;}
            return p;
        }
        else {
            while(p->next) {
                if(p->next->left == p) return p->next;
                p = p ->next;
            }
        }
        return nullptr;
    }
};